<script setup lang="ts">
// 导入日期处理库
import micell from "micell";
// 故障图片弹窗状态
const faultPhotoOpen = ref(false);
// 故障图片URL
const faultPhotoUrl = ref("");

// 导入Ant Design Vue相关组件
import {
  message,
  TableColumnsType,
  TablePaginationConfig,
} from "ant-design-vue";
import { h, onMounted, reactive, ref } from "vue";

import { $endApi } from "@/api/base/index";
/**
 * 获取列表水系统维修列表数据
 * @param current
 * @param pageSize
 */
async function getList(current: number, pageSize: number) {
  const query = {
    page: current,
    size: pageSize,
  };

  const res = await $endApi.v1.water.repair.list(query);
  res.data.items.map((item) => {
    item["undertakingUnit"] = "四川泰合能创科技有限公司";
    // item["createTime"] = micell.date.format(
    //   item["createTime"],
    //   "YYYY-MM-DD HH:mm:ss",
    //   false
    // );

    if (item["updateTime"] != null) {
      item["updateTime"] = micell.date.format(
        item["updateTime"],
        "YYYY-MM-DD HH:mm:ss",
        false
      );
    } else {
      return "无";
    }

    console.log("=======item 2222222222=======\n", item);
    return item;
  });
  console.log("=======getList=======\n", res);
  listdata.value.items = res.data.items;

  paginationSet.total = res.data.meta.total;
  paginationSet.current = res.data.meta.current;
  paginationSet.pageSize = res.data.meta.pageSize;
}

// 组件挂载后初始化数据
onMounted(async () => {
  await getList(1, 10);
});

const listdata = ref<IStandardPageModel<IRepairListModel>>({
  items: [
    {
      id: 131,
      faultArea: "1教",
      faultAddress: "1教302",
      phoneNumber: "13398340080",
      status: 2,
      repairProject: "电灯爆炸",
      undertakingUnit: "锦江学院维修部",
      billingAddress: null,
      faultDescription: "砰的一声就炸了",
      faultPhotos: "这个链接没有图片",
      repairPhotos: null,
      createTime: "2024-08-27T09:41:48.000+00:00",
      updateTime: "2024-08-27T16:38:27.000+00:00",
    },
  ],
  meta: {
    total: 52,
    pages: 52,
    current: 1,
    pageSize: 1,
  },
});

// 分页配置
const paginationSet: TablePaginationConfig = reactive({
  // ... 初始化你的分页配置
  total: listdata.value.meta.total,
  current: listdata.value.meta.current,
  pageSize: listdata.value.meta.pageSize,
  position: ["bottomCenter"],
  defaultPageSize: 10,

  // showTotal: total => `共 ${total} 条数据`,
  // showSizeChanger: true,
  pageSizeOptions: ["10", "15", "20"],
  onChange: (current, pageSize) => {
    current = current;
    pageSize = pageSize;
    //对其分页防抖
    getList(current, pageSize);
    paginationSet.current = current;
    // message.success('点击了');
  },

  /**
   * 当分页大小发生变化时的处理函数
   *
   * 此函数旨在响应分页组件中每页显示数量的变化事件。当用户选择不同的页面大小时，此函数将被调用。
   * 它通过更新paginationSet对象的pageSize属性来设置新的页面大小，并将当前页重置为第一页，以便从新的页面大小开始呈现数据。
   *
   * @param {number} current 当前页码，此参数在此场景中未被使用。
   * @param {number} pageSize 用户选择的每页显示的项数。
   */
  onShowSizeChange(current: number, pageSize: number) {
    paginationSet.pageSize = pageSize; // 修改每页显示的条数
    paginationSet.current = 1; // 重置当前页码为第一页
  },
});

// 故障图片查看方法
function onfaultphotos(src) {
  faultPhotoOpen.value = true;
  console.log("======= onfaultphotos =======\n");
  faultPhotoUrl.value = src;
}

function refreshData() {
  getList(paginationSet.current, paginationSet.pageSize);
}

const updateRepairform = reactive<RequireUpdateReq>({
  id: "",
  phoneNumber: "",
  billingAddress: "",
  status: 0,
  repairPhotos: "",
  undertakingUnit: "",
});

import { IRepairListModel } from "@/api/base/v1/waterSupply.type";
import { IStandardPageModel } from "@/api/base/index.type";

interface IUpdate {
  id: number;
  status: number;
}
async function goFix(id) {
  // columnEditBoolean.value = true;

  updateRepairform.id = id;
  updateRepairform.status = 1;

  const query: IUpdate = {
    id: id,
    status: 1,
  };
  // 过滤掉为空的值
  Object.entries(query).forEach(([key, value]) => {
    if (!value) delete query[key];
  });

  const res = $endApi.v1.water.repair.update(query);

  //   const data1 = api.repairUpdate<RequireUpdateReq>({ ...updateRepairform });
  if (res) {
    refreshData();
    message.success("去维修");
  }
}

function finshFix(id) {
  // columnEditBoolean.value = true;
  updateRepairform.id = id;
  updateRepairform.status = 2;

  const query: IUpdate = {
    id: id,
    status: 2,
  };

  // 过滤掉为空的值
  Object.entries(query).forEach(([key, value]) => {
    if (!value) delete query[key];
  });

  const response = $endApi.v1.water.repair.update(query);

  if (response) {
    refreshData();
    message.success("完成维修");
  }
}

// 表格列配置
const columns: TableColumnsType = [
  {
    title: "编号",
    dataIndex: "id",
    key: "id",
    width: 60,
    align: "center",
  },
  {
    title: "故障区域",
    dataIndex: "faultArea",
    key: "faultArea",
    width: 120,
    align: "center",
  },
  {
    title: "故障地址",
    dataIndex: "faultAddress",
    key: "faultAddress",
    width: 120,
    align: "center",
  },

  {
    title: "维修项目",
    dataIndex: "repairProject",
    key: "repairProject",
    width: 120,
    align: "center",
  },
  {
    title: " 故障描述",
    dataIndex: "faultDescription",
    key: "faultDescription",
    width: 150,
    align: "center",
    ellipsis: true,
  },
  {
    title: "故障照片",
    dataIndex: "faultPhotos",
    key: "faultPhotos",
    width: 150,
    align: "center",
    ellipsis: true,
  },

  {
    title: "状态",
    dataIndex: "status",
    width: 80,
    key: "status",
    align: "center",
    customRender: ({ text, record, index, column }) => {
      if (text == 0) {
        return h("span", { style: { color: "red" } }, "等待维修");
      } else if (text == 1) {
        return h("span", { style: { color: "#00ffff" } }, "维修中");
      } else if (text == 2) {
        return h("span", { style: { color: "green" } }, "已完成");
      }
    },
    filters: [
      {
        text: "等待维修",
        value: 0,
      },
      {
        text: "维修中",
        value: 1,
      },
      {
        text: "已完成",
        value: 2,
      },
    ],
    onFilter: (value: string, record: RepairList) =>
      record.status.toString().includes(value),
  },

  {
    title: "承办单位",
    dataIndex: "undertakingUnit",
    key: "undertakingUnit",
    width: 120,
    align: "center",
  },
  {
    title: "电话号码",
    dataIndex: "phoneNumber",
    key: "phoneNumber",
    width: 120,
    align: "center",
  },

  {
    title: "创建时间  ",
    dataIndex: "createTime",
    key: "createTime",
    width: 120,
    align: "center",
    sorter: (a, b) => {
      console.log("======= a =======\n", a);
      console.log("======= b =======\n", b);
      const date1 = new Date(a.createTime);
      const date2 = new Date(b.createTime);
      return date1.getTime() - date2.getTime();
    },
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    key: "updateTime",
    width: 120,
    align: "center",
    sorter: (a, b) => {
      console.log("======= a =======\n", a);
      console.log("======= b =======\n", b);
      const date1 = new Date(a.createTime);
      const date2 = new Date(b.createTime);
      return date1.getTime() - date2.getTime();
    },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: 120,
    align: "center",
  },
];
</script>

<template>
  <!-- 主要的表格组件，展示维修列表 -->
  <div>
    <a-table
      :labelWrap="true"
      ::label-col="{width:'10px'}"
      :columns="columns"
      :data-source="listdata.items"
      class="table"
      :pagination="paginationSet"
    >
      <!-- 自定义单元格渲染 -->
      <template #bodyCell="{ column, record }">
        <!-- 故障照片列 -->
        <template v-if="column.key === 'faultPhotos'">
          <!-- 显示故障照片 -->
          <div v-if="record.faultPhotos">
            <img
              @click="onfaultphotos(record.faultPhotos)"
              :src="record.faultPhotos"
              :alt="record.description || 'Image'"
              :style="{
                maxWidth: '100px',
                maxHeight: '100px',
                objectFit: 'cover',
              }"
            />
          </div>
          <!-- 如果没有照片，则显示“无” -->
          <p v-else>无</p>
        </template>
        <!-- 维修照片列 -->
        <template v-if="column.key === 'repairPhotos'">
          <!-- 显示维修照片 -->
          <div v-if="record.repairPhotos">
            <img
              :src="record.repairPhotos"
              :alt="record.repairPhotos || 'Image'"
              :style="{
                maxWidth: '100px',
                maxHeight: '100px',
                objectFit: 'cover',
              }"
            />
          </div>
          <!-- 如果没有照片，则显示“无” -->
          <p v-else>无</p>
        </template>
        <!-- 创建时间列 -->
        <template v-if="column.key === 'createTime'">
          <!-- 格式化日期 -->
          {{
            micell.date.format(record.createTime, "YYYY-MM-DD HH:mm:ss", false)
          }}
        </template>

        <!-- 操作列 -->
        <template v-else-if="column.key === 'action'">
          <!-- 操作按钮组 -->
          <span>
            <div v-if="record.status === 0">
              <a-button type="primary  " @click="goFix(record.id)"
                >去维修</a-button
              >
            </div>
            <div v-else-if="record.status === 1">
              <a-button type="primary  " @click="finshFix(record.id)"
                >完成维修</a-button
              >
            </div>

            <a-divider type="vertical" />
          </span>
        </template>
      </template>
    </a-table>

    <!-- 故障图片弹窗 -->
    <div class="other">
      <a-modal
        v-model:open="faultPhotoOpen"
        title="故障图片"
        width="90%"
        @ok="faultPhotoOpen = false"
      >
        <img :src="faultPhotoUrl" alt="Fault Photo" />
      </a-modal>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "../../assets/style/tableDeep.scss";

.table {
  width: 96%;
  height: 100%;
  margin: 10px auto;
  height: 80vh;
  overflow: scroll;

  //布局
  :deep(.ant-layout) {
    display: inline;
  }
}

//model的样式

:deep(.ant-modal-content) {
  display: flex;
  justify-content: center;
  align-items: center;
}
// :deep(.ant-modal .ant-modal-content) {
//     background-color: yellow;
// }
.ant-modal-body {
  padding: 0; /* 移除默认的内边距 */
  margin: 0;
  overflow: hidden; /* 防止滚动条出现 */
}

.ant-modal-body img {
  max-width: 100%; /* 图片宽度不超过模态框宽度 */
  height: auto; /* 自动调整高度 */
}
//model的样式end
</style>
